#include "xtoa.h"

void ultoa(unsigned long value, char *buf, unsigned char base)
{
    char c;
    unsigned char i = 0;
    unsigned long val = value;

    do
    {
        val /= base;
        i++;
    }
    while(val);

    buf[i] = 0;

    while(i)
    {
        c = value % base;
        buf[--i] = c < 10 ? c + '0' : c + 'a' - 10;
        value /= base;
    }
}

void utoa(unsigned int value, char *buf, unsigned char base)
{
    char c;
    unsigned char i = 0;
    unsigned int val = value;

    do
    {
        val /= base;
        i++;
    }
    while(val);

    buf[i] = 0;

    while(i)
    {
        c = value % base;
        buf[--i] = c < 10 ? c + '0' : c + 'a' - 10;
        value /= base;
    }
}

void itoa(int value, char *buf, unsigned char base)
{
    char c;
    unsigned char i = 1;
    int val;

    if(value >= 0 || base != 10)
    {
        utoa((unsigned int)value, buf, base);
        return;
    }

    value = -value;
    val = value;

    do
    {
        val /= base;
        i++;
    }
    while(val);

    buf[i] = 0;

    while(i)
    {
        c = value % base;
        buf[--i] = c < 10 ? c + '0' : c + 'a' - 10;
        value /= base;
    }

    buf[i] = '-';
}

void ltoa(long value, char *buf, unsigned char base)
{
    char c;
    unsigned char i = 1;
    long val;

    if(value >= 0 || base != 10)
    {
        ultoa((unsigned long)value, buf, base);
        return;
    }

    value = -value;
    val = value;

    do
    {
        val /= base;
        i++;
    }
    while(val);

    buf[i] = 0;

    while(i)
    {
        c = value % base;
        buf[--i] = c < 10 ? c + '0' : c + 'a' - 10;
        value /= base;
    }

    buf[i] = '-';
}
